#!/bin/sh

if [ "$1" = "clean" ]; then
    sh scripts/clean.sh
    exit 0
elif [ "$1" = "help" ]; then
    echo "Usage: build.sh <Native | RIO> <Debug | Release> [Rebuild]"
    echo ""
    echo "Build targets: "
    echo " - Native: Use systems default compiler and wpilib install (Unimplemented)"
    echo " - RIO: Use RoboRIO cross compiler and RoboRIO wpilib libraries (Linux only)"
    echo ""
    echo "Build types: "
    echo " - Debug: Enables CMake debug flag"
    echo " - Release: Enables CMake release flag"
    echo ""
    echo "Optionals: "
    echo " - Rebuild: Removes all previous build artifacts"
    echo ""
    exit 0
elif [ -z "$2" ]; then
    # If no arguments are supplied print usage and exit
    echo "Usage: build.sh <Native | RIO> <Debug | Release> [Rebuild]"
    exit 1
fi

if [ "$3" = "Rebuild" ]; then
    sh scripts/clean.sh
fi

BuildTarget=$1
BuildType=$2
ProjRoot=$(pwd)

# Ensure output directory exist
mkdir -p "$ProjRoot"/output/"$BuildTarget"/"$BuildType"

# Install Conan packages
if [ "$BuildTarget" = "RIO" ]; then
    conan install ./build/conan -if "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/conan --build missing --profile "$ProjRoot"/build/conan/roborio.ini -s build_type="$BuildType"
    RIO="ON"
elif [ "$BuildTarget" = "Native" ]; then
    conan install ./build/conan -if "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/conan --build missing -s build_type="$BuildType"
    RIO="OFF"
fi

# Call CMake to build project
cmake -S "$ProjRoot" -B "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/ -DCMAKE_BUILD_TYPE="$BuildType" -DCMakeRIO="$RIO"

# Compile output
cmake --build "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/ --config "$BuildType" --parallel

# Link compile_commands.json for clangd language server functionality
[ -f "$ProjRoot"/compile_commands.json ] && rm compile_commands.json
mv "$ProjRoot"/output/"$BuildTarget"/"$BuildType"/compile_commands.json "$ProjRoot"
